package com.cy.service.impl;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.common.Constant;
import com.cy.entity.Comment;
import com.cy.entity.DiscussPost;
import com.cy.mapper.CommentMapper;
import com.cy.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.service.DiscussPostService;
import com.cy.util.HostHolder;
import com.cy.util.SensitiveFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cy
 * @since 2021-11-08
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private SensitiveFilter sensitiveFilter;

    @Resource
    private DiscussPostService discussPostService;



    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @Override
    public int addComment(Comment comment) {
        if(comment == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = this.baseMapper.insert(comment);

        //改变帖子的评论数量  注意需要判读评论是帖子的还是回复的  帖子的才去更改帖子数量
        if(comment.getEntityType() == Constant.ENTITY_TYPE_POST){
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.eq("entity_type", comment.getEntityType())
                    .eq("entity_id", comment.getEntityId());
            int count = this.baseMapper.selectCount(wrapper);
            DiscussPost discussPost = discussPostService.getById(comment.getEntityId());
            discussPost.setCommentCount(count);
            discussPostService.updateById(discussPost);
        }
        return rows;
    }
}
